package com.bjy.qa.service.manage.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjy.qa.dao.manage.ProjectDao;
import com.bjy.qa.dao.user.UserCompanyProjectDao;
import com.bjy.qa.entity.MyPage;
import com.bjy.qa.entity.ResponsePagingData;
import com.bjy.qa.entity.manage.Project;
import com.bjy.qa.entity.user.UserCompanyProject;
import com.bjy.qa.enumtype.ForwardMode;
import com.bjy.qa.exception.MyException;
import com.bjy.qa.service.manage.IProjectService;
import com.bjy.qa.util.security.SecurityUtils;
import org.apache.commons.lang.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@org.springframework.stereotype.Service
public class ProjectService implements IProjectService {
    @Resource
    ProjectDao projectDao;

    @Resource
    UserCompanyProjectDao userCompanyProjectDao;

    @Override
    public List<Project> selectAll() {
        return projectDao.selectList(new QueryWrapper<>());
    }

    @Override
    public ResponsePagingData list(MyPage<Project> myPage) {
        Page<Project> page = new Page(myPage.getPageNum(), myPage.getPageSize()); // 构造待查询 page 对象
        page.setOrders(myPage.getOrders()); // 设置排序字段

        // 构造待查询 QueryWrapper
        Project project = myPage.getQuery();
        QueryWrapper<Project> queryWrapper = new QueryWrapper<>();
        if (project != null) {
            if (StringUtils.isNotBlank(project.getName())) {
                queryWrapper.like("name", project.getName());
            }
        }

        page = projectDao.selectPage(page, queryWrapper); // 按分页查询

        myPage.setTotalRecords(page.getTotal()); // 设置返回总记录数

        return new ResponsePagingData(myPage, page.getRecords());
    }

    @Override
    public Project selectById(Long id) {
        return projectDao.selectById(id);
    }

    @Override
    public int add(Project project) {
        if (project.isMock() && StringUtils.isBlank(project.getMockPreUrl())) {
            throw new MyException("mock 前置 url 不能为空，请重新输入！");
        } else if (project.getMockPreUrl() != null && project.getMockPreUrl().indexOf("/") >= 0) {
            throw new MyException("mock 前置 url 不能包含 /，请重新输入！");
        } else if (StringUtils.isNotBlank(project.getMockPreUrl()) && (projectDao.selectMockPreUrl(project.getId(), project.getMockPreUrl()) != null)) {
            throw new MyException("mock 前置 url 已存在，请重新输入！");
        }

        if (project.getForwardMode() != null && (project.getForwardMode().getValue() >= ForwardMode.API_NOT_DEFINE.getValue()) && StringUtils.isBlank(project.getForwardUrl())) {
            throw new MyException("选择转发模式后，必须输入转发 url ！");
        }

        int ret = projectDao.insert(project); // 新增项目

        // 创建项目后，自动将当前用户加入项目
        UserCompanyProject userCompanyProject = new UserCompanyProject();
        userCompanyProject.setCompanyId(project.getCompanyId());
        userCompanyProject.setProjectId(project.getId());
        userCompanyProject.setUserId(SecurityUtils.getCurrentUserId());
        userCompanyProjectDao.insert(userCompanyProject);

        return ret;
    }

    @Override
    public int update(Project project) {
        if (project.isMock() && StringUtils.isBlank(project.getMockPreUrl())) {
            throw new MyException("mock 前置 url 不能为空，请重新输入！");
        } else if (project.getMockPreUrl() != null && project.getMockPreUrl().indexOf("/") >= 0) {
            throw new MyException("mock 前置 url 不能包含 /，请重新输入！");
        } else if (StringUtils.isNotBlank(project.getMockPreUrl()) && (projectDao.selectMockPreUrl(project.getId(), project.getMockPreUrl()) != null)) {
            throw new MyException("mock 前置 url 已存在，请重新输入！");
        }

        if (project.getForwardMode() != null && (project.getForwardMode().getValue() >= ForwardMode.API_NOT_DEFINE.getValue()) && StringUtils.isBlank(project.getForwardUrl())) {
            throw new MyException("选择转发模式后，必须输入转发 url ！");
        }

        // 更新数据需要清除 UpdatedTime 和 CreatedTime，否则不会自动更新修改时间
        project.setUpdatedAt(null);
        project.setCreatedAt(null);

        return projectDao.updateById(project);
    }

    @Override
    public int delete(Long id) {
        // 删除 project 前，先判断是不是有用户关联了此 project
        QueryWrapper<UserCompanyProject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", id);
        if (userCompanyProjectDao.selectCount(queryWrapper) > 0) {
            throw new MyException("删除错误。已经有用户关联到此项目，请先删除关联关系！");
        }

        return projectDao.deleteById(id);
    }
}
